<template>
  <div class="app-container">
    <div :gutter="10">
      <el-col v-loading="messageLoading" :span="14" :offset="5" style="background: white">
        <div style="text-align: center; margin: 10px;">
          <el-button size="mini" type="success" :disabled="!current_message.id_customer" @click="showCustomer">
            查看顾客信息
          </el-button>
          <el-button size="mini" type="success" :disabled="!current_message.id_order" @click="showOrder">查看订单信息
          </el-button>
        </div>

        <timeline timeline-theme="lightblue" style="padding-top: 5px" size="mini">
          <timeline-title style="width: auto;display: block;word-wrap: break-word;">
            <a class="mt-href" :href="current_message.title | erpFilter" target="_blank">
              {{ current_message.title }}</a></timeline-title>
          <timeline-item v-for="item in current_message.messages" :key="item.id" color="orange">
            <p>
              <i class="el-icon-date">{{ item.date_upd.split('T')[0] }}</i>
              <i class="el-icon-time">{{ item.date_upd.split('T')[1] }}</i>
              <svg-icon v-if="item.id_employee" icon-class="admin" style="float: right" />
            </p>
            <p class="mt-message" v-html="item.message" />
            <a
              v-if="item.file_name"
              :href="item.file_name"
              target="_blank"
              class="mt-href"
            >Attachments</a>
            <span v-if="item.id_employee" style="color:red;float:right">By admin</span>
          </timeline-item>
        </timeline>
        <el-button
          v-if="current_message.messages.length"
          style="float: right;margin: 10px"
          type="success"
          size="mini"
          :disabled="thread_status"
          @click="handleReply"
        >
          回复
        </el-button>
      </el-col>

    </div>

    <el-dialog
      v-loading="dialogLoading"
      :title="batch? '回复消息(批量)' : '回复消息(单个)'"
      :visible.sync="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >

      <el-form :model="temp" label-width="80px" size="mini">
        <el-form-item label="模板">
          <el-select
            v-model="temp.selected_template"
            placeholder="请选择"
            filterable
            clearable
            size="mini"
            @change="handleSelectTemplate"
          >
            <el-option
              v-for="(item, index) in templates"
              :key="index"
              :label="item.name"
              :value="item.text"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="消息">
          <el-input v-model="temp.text" placeholder="回复内容" type="textarea" :autosize="{ minRows: 6 }" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="send">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { Timeline, TimelineItem, TimelineTitle } from 'vue-cute-timeline'
import { Get as GetTemplates } from '@/api/psmsg/replyTemplate'
import { sendMsg, showMsg, showOrderInfo, showCustomerInfo } from '@/api/psmsg/message'

export default {
  components: {
    Timeline,
    TimelineItem,
    TimelineTitle
  },
  filters: {
    erpFilter(v) {
      return 'http://erp.elicink.com:19870/ps/order?wid=&status=&sort=id_desc&pagesize=50&page=0&isWeb=on&searchKey=' + encodeURI(v)
    }
  },
  data() {
    return {
      messageLoading: false,

      templates: [],
      dialogLoading: false,
      dialogVisible: false,
      temp: {
        selected_template: null,
        text: ''
      },

      thread_status: false,
      current_message: {
        id_customer: null,
        id: null,
        id_order: null,
        title: '',
        messages: []
      },
      batch: false

    }
  },
  computed: {
    id: function() {
      return this.$route.params.id
    }
  },
  created() {
    if (this.id) {
      this.showThread(this.id)
    }
  },
  methods: {
    scrollTop() {
      window.scrollTo(0, 0)
    },
    showThread(v) {
      this.messageLoading = true
      showMsg(v).then(response => {
        this.current_message.messages = response.data
        this.current_message.title = response.email
        this.current_message.id = response.id
        this.current_message.id_customer = response.id_customer
        this.current_message.id_order = response.id_order
        this.current_message.website_id = response.website_id
        this.thread_status = response.state

        this.messageLoading = false
      }).catch(e => {
        this.messageLoading = false
      })
    },
    handleReply(bool_batch) {
      this.resetTemp()
      this.dialogLoading = true
      this.dialogVisible = true
      GetTemplates().then(response => {
        this.templates = response.data.data
        this.dialogLoading = false
      }).catch(e => {
        this.dialogLoading = false
      })
    },
    handleSelectTemplate(v) {
      this.temp.text = v
    },
    send() {
      this.dialogLoading = true
      sendMsg({
        id: this.current_message.id,
        message: this.temp.text
      }).then(response => {
        this.$notify({
          title: '成功',
          message: '发送消息成功',
          type: 'success',
          duration: 20000
        })
        this.dialogVisible = false
        this.dialogLoading = false
        this.messageLoading = false
        this.scrollTop()
      }).catch(e => {
        this.dialogLoading = false
      })
    },
    resetTemp() {
      this.temp = {
        selected_template: null,
        text: 'Dear Customer:\n\n\nCustomer Service',
        id_customer: null,
        id_order: null,
        messages: []
      }
    },
    showCustomer() {
      this.messageLoading = true
      showCustomerInfo({
        id: this.current_message.id,
        id_customer: this.current_message.id_customer
      }).then(response => {
        this.messageLoading = false
        this.$alert(this.liFilter(response.data), 'Customer Info', {
          dangerouslyUseHTMLString: true
        })
      }).catch(e => {
        this.messageLoading = false
      })
    },
    showOrder() {
      this.messageLoading = true
      showOrderInfo({
        id: this.current_message.id,
        id_order: this.current_message.id_order,
        website_id: this.current_message.website_id
      }).then(response => {
        this.messageLoading = false
        this.$alert(this.liFilter(response.data), 'Order Info', {
          dangerouslyUseHTMLString: true
        }).catch(e => {
          this.messageLoading = false
        })
      })
    },
    liFilter(v) {
      const href_words = ['order_id', 'order_reference', 'email']
      return '<table border="1">' + v.map(k => {
        if (href_words.includes(k[0])) {
          const url = 'http://erp.elicink.com:19870/ps/order?wid=&status=&sort=id_desc&pagesize=50&page=0&isWeb=on&searchKey=' + encodeURI(k[1])
          const link = '<a style="text-decoration: underline;color: #409EFF;" href=' + url + ' target="_blank">' + k[1] + '</a>'
          return '<tr><th>' + k[0] + '</th><th>' + link + '</th></tr>'
        } else {
          return '<tr><th>' + k[0] + '</th><th>' + k[1] + '</th></tr>'
        }
      }
      ).join('') + '</table>'
    }
  }
}
</script>

<style scoped>
  .top >>> .el-select .el-input {
    width: 350px;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top >>> .el-input-group__append .el-button--default {
    color: white;
    background-color: #409EFF;
    border: 1px solid #409eef;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .app-container >>> em {
    color: red;
  }

  .mt-message {
    padding: 0 0 0 10px;
    border-left: 2px solid #ccc;

    word-break: normal;
    width: auto;
    display: block;
    white-space: pre-wrap;
    word-wrap: break-word;
  }

  .clearfix:before,
  .clearfix:after {
    display: block;
    content: '';
    clear: both;
    height: 0;
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .top {
    margin: 20px;
  }

  .top >>> .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .mt-href {
    text-decoration: underline;
    color: #409EFF;
  }

  .m-red {
    color: red;
  }

  .m-blue {
    color: #409EFF;
  }

  .mt-form-item-left {
    width: 26%;
    margin-right: 0;
  }

  .mt-form-item-left >>> .el-form-item__content {
    width: calc(100% - 80px);
  }

  .mt-form-item-left >>> .el-select {
    width: 100%;
  }

  .mt-form-item-search >>> .el-form-item__content {
    width: 100%;
  }
</style>
